<template>
    <div style="position: relative; width: 100%; height: 90vh">
        <div class="card">
            <div class="card-content">
                <div v-for="(item, index) in cardList" :key="index">
                    <template v-if="item.key !== 'pksm' && item.key !== 'xgfj' && item.key !== 'bcsm' && item.key !== 'gldw' && item.key !== 'zclx' && item.key !== 'ssxm'">
                        <van-field v-model="form[item.value]" :label="item.name" :right-icon="item.icon" @click="handleVal(item)" @input="onFieldInput(item.value, $event)" placeholder="请输入..." />
                    </template>
                    <template v-if="item.key == 'gldw' || item.key == 'zclx' || item.key == 'ssxm'">
                        <van-field v-model="form[item.value]" :label="item.name"  @click="handleVal(item)"  right-icon="arrow" @input="onFieldInput(item.value, $event)" placeholder="请选择..." />
                    </template>
                    <template v-if="item.key == 'pksm' || item.key == 'bcsm'">
                        <van-field v-model="form[item.value]" rows="2" autosize :label="item.name" type="textarea" maxlength="50" placeholder="请输入..." show-word-limit @input="onFieldInput(item.value, $event)" />
                    </template>
                    <template v-if="item.key == 'xgfj'">
                        <uploadFile :attachmentList="tableData" @uploadFileComplete="uploadFileComplete" class="is-upload"></uploadFile>
                    </template>
                </div>
            </div>
        </div>
        <div>
            <div style="display: flex; justify-content: center" class="btn">
                <div class="btnlist">
                    <div style="width: 50%; padding: 10px" :class="[type == 1 ? 'activeBtn' : '']" @click="closeBtn">取消</div>
                    <div style="width: 50%; padding: 10px" :class="[type == 2 ? 'activeBtn2' : '']" @click="submitBtn">确认</div>
                </div>
            </div>
        </div>
        <van-popup v-model:show="showPicker" position="bottom">
            <van-datetime-picker v-model="currentDate" @confirm="showPicker = false" @cancel="showPicker = false" type="date" title="选择年月日" />
        </van-popup>
    </div>
</template>

<script>
import UploadFile from '../../../components/uploadFile.vue'
import {formatDT} from '@/utils/utils'
import backMixin from '../../../mixins/backMixin'
export default {
    mixins: [backMixin],
    components: {
        UploadFile
    },
    name: 'card',
    props: {
   taskId:{
        type:String,
        default:''
   },
        Objapi:{
            type:String,
        },
  
        cardList: {
            type: Array,
            default: ''
        },
        mode: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            type: 1,
            tableData: [],
            showPicker: false,
            currentDate: new Date(),
            pickingField: '',

            form: {}
        }
    },
    watch: {

    },
    mounted() {

      //  this.form = this.formData || {}
       // Avoid mutating Vuex-bound form data directly
       // Instead, create a shallow copy and assign formatted values
    //    this.form = Object.assign({}, this.formData, {
    //      beginDate: formatDT(this.form.beginDate, 'yyyy-MM-dd'),
    //      endDate: formatDT(this.form.endDate, 'yyyy-MM-dd')
    //    })
     console.log(this.form,'card init form')
    },
    methods: {
        //上传返回数据
        uploadFileComplete(file) {
            console.log(file,'file')
            if (!Array.isArray(this.form.attachmentWebDtoList)) this.$set(this.form, 'attachmentWebDtoList', [])
            this.form.attachmentWebDtoList.push(file)
            // notify parent of change
            this.$emit('formChange', { key: 'attachmentWebDtoList', value: this.form.attachmentWebDtoList })
      
        },
       setformdata(v) {
    console.log('setformdata received:', v)
  
    // 确保form是响应式对象
    if (!this.form || typeof this.form !== 'object') {
        this.form = {}
    }
    
    // 使用Vue.set确保响应式更新
    Object.keys(v).forEach(key => {
        this.$set(this.form, key, v[key])
    })
    
    console.log('form after setformdata:', this.form)
    
    // 强制更新视图
    this.$nextTick(() => {
        try {
            this.$forceUpdate()
        } catch (e) {
            console.log('forceUpdate failed:', e)
        }
    })
},
        onFieldInput(key, val) {
           
            this.$set(this.form, key, val)
         
            this.$emit('formChange', { key, value: val })
        },
        handleVal(item) {
            console.log(item)
            // 支持任务开始/结束时间弹出选择器
            if (item.key == 'rwkssj' || item.key == 'rwjssj') {
                // 记录当前正在编辑的字段名（例如 'beginDate' / 'endDate'）
                this.pickingField = item.value
                // 尝试用已有值初始化日期选择器
                try {
                    const val = this.form[item.value]
                    if (val) {
                        const d = new Date(val)
                        if (!isNaN(d.getTime())) this.currentDate = d
                    }
                } catch (e) {
                    // ignore
                }
                this.showPicker = true
            }
            this.$emit('cardItem', item)
            if(item.key == 'ssxm'){
                this.$router.push({ name: 'assectType', params: { key: 'ssxm' }, query: { returnName: this.$route.name } })
            }
            if(item.key == 'zclx'){
                this.$router.push({ name: 'assectType', params: { key: 'zclx' }, query: { returnName: this.$route.name } })
            }
            if(item.key == 'gldw'){
                this.$router.push({ name: 'assectType', params: { key: 'gldw' }, query: { returnName: this.$route.name } })
            }
        },
      async  submitBtn() {
            this.type = 1
            try {
                let res;
                if(this.mode == 'pk'){
                    this.form.action = 2
                    res = await this.$Geting(this.Objapi, this.form) //盘亏
                }else{
                    if(this.mode == 'py'){
                        this.form.stocktakingResult = 1//盘盈
                        this.form.taskId = this.taskId
                         this.form.action = 1
                         this.form.attachmentWebDtoList=[]
                         res = await this.$Posting(this.Objapi, this.form)
                    }else{
                        //编辑任务
                         res = await this.$Posting(this.Objapi, this.form)
                    }
                   
                }
                
                // 不再使用 Vuex 回填，使用路由 backData 作为统一回传方式
                if (res.code === '0' && res.data) {
                    console.log(res, 'res')
                    // 先保留要跳转的 taskId，再清空表单
                    const targetId = this.form.taskId || this.taskId || (this.$route && this.$route.params && this.$route.params.id)
                    this.form = {}
                    this.$toast('操作成功')
                    try {
                        // 使用路由替换跳回 detailTask，并携带 refresh 时间戳触发刷新
                        if (targetId) {
                            this.$router.replace({ name: 'detailTask', params: { id: targetId }, query: { refresh: Date.now() } })
                        } else {
                            // 若未找到 id，退回到上一页作为兜底
                            this.navigateBack()
                        }
                    } catch (e) {
                        // 兜底回退
                        this.navigateBack()
                    }
                } else {
                    this.$toast(res.message)
                }
            }catch(error){
                console.log(error,'error')
                this.$toast(error)
            }
        },
        closeBtn() {
            this.type = 2
            this.navigateBack()
            this.form={}
        }
    },
    watch: {
        // 当选择器关闭时，将选择的日期回填到表单
        showPicker(newVal, oldVal) {
            if (oldVal === true && newVal === false && this.pickingField) {
                // 格式化为 yyyy-MM-dd，并同步到父组件
                let formatted
                try {
                    formatted = formatDT(this.currentDate, 'yyyy-MM-dd')
                    this.$set(this.form, this.pickingField, formatted)

                } catch (e) {
                    formatted = this.currentDate
                    this.$set(this.form, this.pickingField, formatted)
                }
                // emit to parent so parent can update its form
                this.$emit('formChange', { key: this.pickingField, value: formatted })
                this.showPicker=false
                // 清空 pickingField
                this.pickingField = ''
            }
        }
    }
}
</script>

<style lang="less" scoped>
.activeBtn {
    border-radius: 12.5px 0 17.5px 12.5px;
    background-color: #fff;
    color: #000;
}

.activeBtn2 {
    border-radius: 0px 12.5px 12.5px 12.5px;
    background-color: #fff;
    color: #000;
}

.btn {
    position: absolute;
    bottom: 100px;
    width: 60vw;
    left: 20vw;
}

.btnlist {
    display: flex;
    border: 1px solid #3772ff;
    background-color: #3772ff;
    border-radius: 12.5px;
    text-align: center;
    width: 305px;
    color: #fff;
}

.title {
    font-size: 1.2em;
}

.card {
    background: #ffffff;
    /* 白色背景 */
    border-radius: 10px;
    /* 圆角 */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    /* 阴影效果 */
    margin: 15rpx 0rpx;
    /* 卡片之间的间距 */
}

.card-content {
    /* 垂直居中 */
    padding: 10px 10px;
    /* 内边距 */
}
</style>
